'use strict';

const readline = require('readline');

const fs = require("fs");

const path = require('path');

module.exports = async function (ctx) {
    undefined

    let filePath = path.resolve(__dirname, '../../../../public/assets/a.txt');

    try {
        undefined

        const result = await readFile(filePath);

        //区分结果页和情景页

        let atom_wise = [];

        let atom_card = [];

        let atom_wise_sum = 0;

        let atom_card_sum = 0;

        for (let i = 0; i < result.length; i++) {
            undefined

            // 遍历单个卡片

            for (let j = 0; j < result[i].length; j++) {
                undefined

                // 结果页卡片

                if (result[i][j] === '1') {
                    undefined

                    atom_wise_sum++;

                    atom_wise.push(result[i]);

                }

                // 情景页卡片

                if (result[i][j] === '2') {
                    undefined

                    atom_card_sum++;

                    atom_card.push(result[i]);

                }

            }

        }

        ctx.json({
            undefined

            status: 0,

            msg: '成功',

            atom_wise_sum,

            atom_card_sum,

            atom_wise,

            atom_card

        });

    } catch (e) {
        undefined

        console.error(e);

        ctx.json({
            undefined

            status: 1,

            msg: '失败'

        });

    }

};

function readFile(filePath) {
    undefined

    console.log('开始读取文件...');

    let input = fs.createReadStream(filePath);

    const rl = readline.createInterface({
        undefined
        input

    });

    let result = [];

    let lineData;

    return new Promise((resolve, reject) => {
        undefined

        rl.on('line', (line) => {
            undefined

            if (line.split(/\s+/)[4] === 'atom') {
                undefined

                lineData = line.split(/\s+/);

                result.push(lineData);

            }

        });

        rl.on('close', (line) => {
            undefined

            console.log("读取文件完毕！");

            resolve(result);

        });

        rl.on('error', reject);

    });
}
